package control;

import com.alibaba.fastjson.JSON;
import entity.Article;
import entity.Dept;
import entity.PageEntity;
import entity.User;
import service.ListService;
import utils.FileUploadUtils;

import javax.servlet.ServletContext;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;
import java.util.Date;
import java.util.List;
import java.util.Map;

@WebServlet("/internal/*")
public class ListServlet extends BaseServlet {
    private ListService listService = new ListService();
    private PageEntity pageEntity = new PageEntity();

    public void addSave(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        request.setCharacterEncoding("utf-8");
        response.setCharacterEncoding("utf-8");
        Map<String, String> param = getParam(request);
        Long articleId = Long.parseLong(param.get("articleId"));

        //是否收藏此文章
        Integer count = listService.saveArticle(articleId,loginUser.getId());
        if (count == 0) {
            //没有收藏这个文章
            //收藏文章
            listService.add(articleId,loginUser.getId());
        }else{
            //取消收藏
            listService.deleteArticle(articleId,loginUser.getId());
        }
    }

    /**
     * 文章的详细信息
     * @param request
     * @param response
     * @throws ServletException
     * @throws IOException
     */
    public void findByArticleInfo(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        request.setCharacterEncoding("utf-8");
        response.setCharacterEncoding("utf-8");
        Map<String, String> param = getParam(request);
        Long articleId = Long.parseLong(param.get("articleId"));

        //查找文章信息
        Article article = listService.findByArticleInfo(articleId);

        //浏览量＋1
        listService.addBrowseCount(articleId);

        //收藏次数
        Integer saveCount = listService.saveArticleCount(articleId);

        request.setAttribute("saveCount", saveCount);

        //我关注的人里关注这篇文章的人
        List<User> userList = listService.addAndSave(articleId,loginUser.getId());

        request.setAttribute("userList", userList);

        //是否收藏此文章
        Integer count = listService.saveArticle(articleId,loginUser.getId());
        if (count == 0) {
            //没有收藏这个文章
            request.setAttribute("save", "0");
        }else{
            request.setAttribute("save", "1");
        }

        request.setAttribute("article", article);

        request.getRequestDispatcher("/html/article_detail.jsp").forward(request, response);

    }

    /**
     * 收藏文章＋分页
     * @param request
     * @param response
     * @throws ServletException
     * @throws IOException
     */
    public void SaveArticle(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        request.setCharacterEncoding("utf-8");
        response.setCharacterEncoding("utf-8");
        Map<String, String> param = getParam(request);
        Integer currPage = Integer.parseInt(param.get("currPage"));
        String title = param.get("title");

        PageEntity<Article> saveList = listService.SaveArticle(loginUser.getId(),currPage,title);
        request.setAttribute("saveList", saveList);
        request.setAttribute("title", title);

        request.getRequestDispatcher("/html/article_collect.jsp").forward(request, response);
    }
    /**
     * 发布文章
     * @param request
     * @param response
     * @throws ServletException
     * @throws IOException
     */
    public void PublishArticle(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        request.setCharacterEncoding("utf-8");
        response.setCharacterEncoding("utf-8");
        Map<String, String> param = getParam(request);
        Article article = new Article();
        //当前页面
        Integer currPage = Integer.parseInt(param.get("currPage"));
        String content = param.get("content");
        String title = param.get("title");
        article.setTitle(title);
        article.setBrowseCount(0L);
        article.setContent(content);
        article.setPublishRealName(loginUser.getRealName());
        article.setPublishDate(new Date());
        article.setUserId(loginUser.getId());

        listService.addArticle(article);

        response.sendRedirect("/internal/findPageAllArticle?currPage=1");

    }

    /**
     * 所有文章＋分页
     * @param request
     * @param response
     * @throws ServletException
     * @throws IOException
     */
    public void findPageAllArticle(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        request.setCharacterEncoding("utf-8");
        response.setCharacterEncoding("utf-8");
        Map<String, String> param = getParam(request);

        //搜索信息
        String articleName = param.get("articleName");

        //当前页面
        Integer currPage = Integer.parseInt(param.get("currPage"));

        //所有的文章信息
        PageEntity<Article> articleList = listService.findPageAllArticle(currPage);

        //搜索出来的文章信息
        PageEntity<Article> articleLikeList = listService.findPageLikeArticle(currPage,articleName);

        request.setAttribute("articleList", articleList);
        request.setAttribute("articleLikeList", articleLikeList);
        request.setAttribute("articleName", articleName);

        request.getRequestDispatcher("/html/article.jsp").forward(request, response);
    }

    /**
     * 前端关注回响
     * @param request
     * @param response
     * @throws ServletException
     * @throws IOException
     */
    public void focus(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        request.setCharacterEncoding("utf-8");
        response.setCharacterEncoding("utf-8");
        Map<String, String> param = getParam(request);

        String userId = param.get("userId");

        //查询数据库中有没有这条数据
        Integer has = listService.isFocus(userId,loginUser.getId());

        if (has == 0) {
            //有这条数据
            listService.addFocus(userId,loginUser.getId());
            response.getWriter().write("0");
        }else {
            listService.removeFocus(userId,loginUser.getId());
            response.getWriter().write("1");
        }
        


    }
    /**
     * 查询关注的用户信息
     * @param request
     * @param response
     * @throws ServletException
     * @throws IOException
     */
    public void findPageFocus(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        request.setCharacterEncoding("utf-8");
        response.setCharacterEncoding("utf-8");
        Map<String, String> param = getParam(request);

        //当前页面
        Integer currPage = Integer.parseInt(param.get("currPage"));

        PageEntity<User> focusList = listService.findPageFocus(currPage,loginUser.getId());

        request.setAttribute("focusList", focusList);

        request.getRequestDispatcher("/html/my_user.jsp").forward(request, response);
    }
    /**
     * 头像上传
     * @param request
     * @param response
     * @throws ServletException
     * @throws IOException
     */
    public void uploadPic(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        request.setCharacterEncoding("utf-8");
        response.setCharacterEncoding("utf-8");

        //上传到upload路径，并且返回文件名称
        String upload = FileUploadUtils.upload("/upload", request);

        loginUser.setPic(upload);

        //修改数据库中的pic
        listService.uploadPic(loginUser);

        //将图片的互联网地址写给前端
        writerObjToString(response, upload);
    }

    /**
     * 修改登录者信息
     * @param request
     * @param response
     * @throws ServletException
     * @throws IOException
     */
    public void update(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        request.setCharacterEncoding("utf-8");
        response.setCharacterEncoding("utf-8");

        User user = (User) request.getSession().getAttribute("loginUser");
        Map<String, String> param = getParam(request);

        Long id = loginUser.getId();
        user.setRealName(param.get("name"));
        user.setDeptId(Long.parseLong(param.get("deptId")));
        user.setPhone(param.get("phone"));
        user.setAge(Long.parseLong(param.get("age")));
        user.setInfo(param.get("info"));
        user.setGender(param.get("gender"));

        String isSecret = param.get("isSecret");

        String deptName = param.get("deptName");

        if (isSecret.equals("0")) {
            //代表用户是私密
            user.setIsSecret("0");
        }else {
            user.setIsSecret("1");
        }

        listService.update(user);

        response.sendRedirect("/internal/userDetail");
    }

    /**
     * 查看user的详细信息
     *
     * @param request
     * @param response
     * @throws ServletException
     * @throws IOException
     */
    public void userDetail(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        Map<String, String> param = getParam(request);
        String flag = param.get("flag");

        if ("detail".equals(flag)) {
            Long userID = Long.parseLong(param.get("userID"));
            //查看别人的详细信息

            //1、查看用户的详细信息
            User byUser = listService.findByUserDetail(userID);

            request.setAttribute("user", byUser);

            //2、查看关注数量
            Integer count = listService.countUser(userID);

            request.setAttribute("count", count);

            //3、被看数＋1
            listService.addLock(userID);

            request.getRequestDispatcher("/html/user_detail.jsp").forward(request, response);

        } else {
            //查看自己的信息
            Long id = loginUser.getId();

            //1、查看用户的详细信息
            User byUser = listService.findByUserDetail(id);

            request.setAttribute("user", byUser);

            //2、查看关注数量
            Integer count = listService.countUser(id);

            request.setAttribute("count", count);

            //3、被看数＋1
            listService.addLock(id);

            //4、所属部门
            List<Dept> deptList = listService.findByDept();

            request.setAttribute("deptList", deptList);

            request.getRequestDispatcher("/html/user_look.jsp").forward(request, response);


        }
    }


    /**
     * 查询部门对应的员工
     *
     * @param request
     * @param response
     * @throws ServletException
     * @throws IOException
     */
    public void findByUser(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        response.setContentType("application/json;charset=UTF-8");

        Map<String, String> param = getParam(request);
        String deptId = param.get("deptId");
        List<User> userList = listService.findByUser(deptId);

        response.getWriter().write(JSON.toJSONString(userList));
    }

    /**
     * 查询所有部门和下面对应的员工
     *
     * @param request
     * @param response
     * @throws ServletException
     * @throws IOException
     */
    public void departments(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        List<Map<String, Object>> deptList = listService.findDepartments();

        request.setAttribute("deptList", deptList);

        request.getRequestDispatcher("/html/department.jsp").forward(request, response);


    }

    /**
     * 根据分页来显示查询到的数据
     *
     * @param request
     * @param response
     * @throws ServletException
     * @throws IOException
     */
    public void findPage(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        Map<String, String> param = getParam(request);

        //当前页
        Integer currPage = Integer.parseInt(param.get("currPage"));
        //搜索条件
        String realName = param.get("realName");

        //根据条件查询分页信息
        PageEntity<User> pageEntity = listService.findByPage(currPage, realName);

        //查询关注信息
        List<Long> FocusIdList = listService.findByFocus(loginUser.getId());

        request.setAttribute("FocusIdList", FocusIdList);
        request.setAttribute("pageEntity", pageEntity);
        request.setAttribute("realName", realName);
        request.getRequestDispatcher("/html/user.jsp").forward(request, response);

    }

    /**
     * 根据搜索信息查找对应的数据
     *
     * @param request
     * @param response
     * @throws ServletException
     * @throws IOException
     */
    public void searchValue(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {

        //获取前端发送的数据
        String realName = request.getParameter("realName");

        List<User> userList = listService.searchValue(realName);

        HttpSession session = request.getSession();
        session.setAttribute("userList", userList);
        request.setAttribute("realName", realName);

        request.getRequestDispatcher("/html/user.jsp").forward(request, response);

    }

    /**
     * 查询所有用户信息
     */
    public void findAll(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {

        //获取会话域中的loginUser的信息
        HttpSession session = request.getSession();
        User user = (User) session.getAttribute("loginUser");

        List<User> userList = listService.findAll(user);

        session.setAttribute("userList", userList);

        request.getRequestDispatcher("/html/user.jsp").forward(request, response);

    }
}

